package order

import (
	"context"
	"encoding/json"
	"sale-admin/internal/app/web/schema"
	"sale-admin/internal/models"
	"time"

	"github.com/samber/lo"
	"gorm.io/gorm"
)

type OrderNotifyService struct{}

func (ons OrderNotifyService) SaveNotifyLog(ctx context.Context, db *gorm.DB, outTradeNo, source, msg, uniqueID string) {
	if outTradeNo != "null" {
		var orderInfo models.MaOrder
		var orderCount int64
		db.Model(&models.MaOrder{}).
			Where("end_out_trade_no = ?", outTradeNo).
			Take(&orderInfo).
			Count(&orderCount)
		//写入订单回调记录表
		var logData models.MaOrderNotify
		logData.ID = orderInfo.MerchantID
		logData.MerchantID = orderInfo.MerchantID
		logData.OutTradeNo = outTradeNo
		logData.Source = source
		logData.Msg = msg
		logData.AddTime = time.Now()
		db.Model(&models.MaOrderNotify{}).Create(&logData)
		if orderCount != 0 {
			var CountDataList []schema.OrderGoodsDetailOld
			json.Unmarshal([]byte(orderInfo.CountData), &CountDataList)
			var GoodsList []string
			for _, v := range CountDataList {
				if !lo.Contains(GoodsList, v.GoodsID) {
					GoodsList = append(GoodsList, v.GoodsID)
				}
			}
			if source == "WeChat" {
				//写入微信用户复购率表
				var BatchInsertData []models.MaWechatRate
				for _, v := range GoodsList {
					var orderCount int64
					db.Model(&models.MaWechatRate{}).
						Where("out_trade_no = ?", outTradeNo).
						Count(&orderCount)
					if orderCount == 0 {
						var item models.MaWechatRate
						item.UniqueID = uniqueID
						item.Type = 1 //微信
						item.OutTradeNo = outTradeNo
						item.SalesID = orderInfo.SalesID
						item.RobotName = orderInfo.RobotName
						item.GoodsID = v
						item.Count = 1
						item.AddTime = time.Now()
						BatchInsertData = append(BatchInsertData, item)
					}
				}
				if len(BatchInsertData) > 0 {
					db.Model(&models.MaWechatRate{}).CreateInBatches(&BatchInsertData, 10)
				}
			} else if source == "Alipay" {
				//写入支付宝用户复购率表
				var BatchInsertData []models.MaWechatRate
				for _, v := range GoodsList {
					var orderCount int64
					db.Model(&models.MaWechatRate{}).
						Where("out_trade_no = ?", outTradeNo).
						Count(&orderCount)
					if orderCount == 0 {
						var item models.MaWechatRate
						item.UniqueID = uniqueID
						item.Type = 2 //支付宝
						item.OutTradeNo = outTradeNo
						item.SalesID = orderInfo.SalesID
						item.RobotName = orderInfo.RobotName
						item.GoodsID = v
						item.Count = 1
						item.AddTime = time.Now()
						BatchInsertData = append(BatchInsertData, item)
					}
				}
				if len(BatchInsertData) > 0 {
					db.Model(&models.MaWechatRate{}).CreateInBatches(&BatchInsertData, 10)
				}
			}
		}
	} else {
		//写入订单回调记录表
		var logData models.MaOrderNotify
		logData.MerchantID = ""
		logData.OutTradeNo = outTradeNo
		logData.Source = source
		logData.Msg = msg
		logData.AddTime = time.Now()
		db.Model(&models.MaOrderNotify{}).Create(&logData)
	}
}
